package com.cd.javacxy.module.web.controller;

import com.cd.javacxy.common.model.entity.SessionUser;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.query.UserFriendQuery;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.model.vo.CxyUserVo;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.module.base.BaseController;
import com.cd.javacxy.module.web.service.CxyUserFriendService;
import com.cd.javacxy.module.web.service.CxyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import java.net.URLEncoder;

/**
 * CxyUser的路由接口服务
 *
 * @author yhy
 */
@Controller
@Validated
@Slf4j
public class CxyUserController extends BaseController {

    /**
     * CxyUserService服务
     */
    private CxyUserService cxyUserService;
    private CxyUserFriendService userFriendService;

    @Autowired
    public void setCxyUserService(CxyUserService cxyUserService) {
        this.cxyUserService = cxyUserService;
    }

    @Autowired
    public void setUserFriendService(CxyUserFriendService userFriendService) {
        this.userFriendService = userFriendService;
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResponse loginPage(HttpServletRequest request, HttpServletResponse response,
                                  @NotBlank(message = "请填写账号")
                                  @Email(message = "账号格式不正确")
                                  @RequestParam(name = "account") String account,
                                  @NotBlank(message = "请填写密码")
                                  @RequestParam(name = "password") String password,
                                  @RequestParam(name = "rememberMe", required = false, defaultValue = "1") String rememberMe) {
        final String one = "1";
        HttpSession session = request.getSession();
        AjaxResponse.AjaxResponseBuilder<Object> builder = AjaxResponse.builder();
        try {
            CxyUserVo userVo = cxyUserService.login(account, password);
            SessionUser sessionUser = new SessionUser();
            sessionUser.setUserId(userVo.getUserId());
            sessionUser.setUserName(userVo.getUserName());
            sessionUser.setUserIcon(userVo.getUserIcon());
            session.setAttribute(Constants.SESSION_USER_KEY, sessionUser);
            // 清除之前的Cookie 信息
            if (one.equals(rememberMe)) {
                String info = URLEncoder.encode(account, "utf-8") + "|";
                Cookie cookie = new Cookie(Constants.COOKIE_USER_INFO, null);
                cookie.setPath("/");
                cookie.setMaxAge(0);
                // 建用户信息保存到Cookie中
                cookie = new Cookie(Constants.COOKIE_USER_INFO, info);
                cookie.setPath("/");
                // 设置最大生命周期为1年。
                cookie.setMaxAge(31536000);
                response.addCookie(cookie);
            } else {
                Cookie cookie = new Cookie(Constants.COOKIE_USER_INFO, null);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            builder.errorMsg(ResponseCode.SUCCESS.getDesc());
            builder.code(ResponseCode.SUCCESS.getCode());
        } catch (Exception e) {
            builder.errorMsg(ResponseCode.SERVERERROR.getDesc());
            builder.code(ResponseCode.SERVERERROR.getCode());
            log.error("用户登录失败,账号:{}", account, e);
        }
        return builder.build();
    }

    @GetMapping(value = "/user/{userId}")
    public ModelAndView user(HttpSession session, @PathVariable Integer userId) {
        ModelAndView view = new ModelAndView("user/home");
        try {
            CxyUserVo user = this.cxyUserService.findUserInfo4UserHome(userId);
            view.addObject("user", user);
            UserFriendQuery userFriendQuery = new UserFriendQuery();
            userFriendQuery.setUserId(this.getUserId(session));
            userFriendQuery.setFriendUserId(userId);
            view.addObject("focusType", this.userFriendService.findFocusType4UserHome(userFriendQuery));
            //获取粉丝和关注数量
            userFriendQuery = new UserFriendQuery();
            userFriendQuery.setFriendUserId(userId);
            view.addObject("fansCount", this.userFriendService.findCount(userFriendQuery));
            userFriendQuery = new UserFriendQuery();
            userFriendQuery.setUserId(userId);
            view.addObject("focusCount", this.userFriendService.findCount(userFriendQuery));
        } catch (Exception e) {
            log.error("获取用户信息失败：", e);
            view.setViewName("redirect:" + Constants.ERROR_404);
            return view;
        }
        return view;
    }


}
